#!/usr/bin/env node

const fs = require('fs'),
      join = require('path').join,
      tmp = process.argv[2],
      file = process.argv[3],
      dir = 'sysFile';

switch(tmp){
  case "-list":
    let arr = [];
    let arry = [];
    const files =  fs.readdirSync(dir);
    files.forEach(function(item,i){
        let stat = fs.lstatSync(`./sysFile/${item}`);
        if(!stat.isDirectory()){
          let obj = {};
          obj.fileName = item;
          obj.fileSize = stat.size; 
          arry.push(stat.size);
          JSON.stringify(obj);
          arr.push(obj);
        }
    })
       
    function sortfunc(a,b){
      return a-b;
    }
    arry.sort(sortfunc);
    let n=0;
    let temp;
    for(let i=0;i<arr.length;i++){
      if(arry[n]==arr[i].fileSize){
        temp = arr[i];
        arr[i]=arr[n];
        arr[n]=temp;
        n++;
      }
    }             
    console.log(arr);
    break;

  case "-show":
    try{
      console.log(fs.readFileSync(`./${dir}/${file}`).toString('utf8'));
    }catch(err){
      console.log("该文件不存在！");
      process.exit(1);
    }
    break;

  case "-del":
    if(typeof(file)==='undefined'){
      console.error('请输入要删除的文件名或者是目录名！');
      process.exit(1);
    }
    if(!fs.existsSync(`./${dir}/${file}`)){
      console.log("该文件不存在！");
      process.exit(2);
    }
    if(fs.statSync(`./${dir}/${file}`).isFile()){
      fs.unlinkSync(`./${dir}/${file}`);
      console.log(`${file}删除成功！`);
      process.exit(3);
    }
    if(fs.statSync(`./${dir}/${file}`).isDirectory()){
      deleteDir(`./${dir}/${file}`);
      console.log(`${file}删除成功！`)
      process.exit(4);
    }
    function deleteDir(folder){
      let fill = fs.readdirSync(folder);
      for(let i=0;i<fill.length;i++){
        let filee = join(folder,fill[i]);
        if(fs.statSync(filee).isFile()){
          fs.unlinkSync(filee);
          continue;
        }
        if(fs.statSync(filee).isDirectory()){
          deleteDir(filee);
        }
      }
      fs.rmdirSync(folder);
    }
    break;

}


